/*
 * @lc app=leetcode.cn id=563 lang=cpp
 *
 * [563] 二叉树的坡度
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
  int ans;
  int findTilt(TreeNode* root)
  {
    ans = 0;
    DFS(root);
    return ans;
  }

  int DFS(TreeNode* root)
  {
    if (root) {
      int l_sum = DFS(root->left);
      int r_sum = DFS(root->right);
      ans += (abs(r_sum - l_sum));
      return l_sum + r_sum + root->val;
    }
    return 0;
  }
};
// @lc code=end
